# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Martell Malone <martellmalone@gmail.com>

_realname=tools
pkgbase=mingw-w64-${_realname}-git
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
provides=("${MINGW_PACKAGE_PREFIX}-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=9.0.0.6166.0a00d0ea
pkgrel=1
_commit='0a00d0ea9b2cff3f22b276201fd22daee162ff07'
pkgdesc="MinGW-w64 tools"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://mingw-w64.sourceforge.io/"
license=('custom')
groups=("${MINGW_PACKAGE_PREFIX}-toolchain")
makedepends=("git" "${MINGW_PACKAGE_PREFIX}-gcc" "${MINGW_PACKAGE_PREFIX}-libmangle")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
options=('staticlibs' '!emptydirs')
source=("mingw-w64"::"git+https://git.code.sf.net/p/mingw-w64/mingw-w64#commit=$_commit")
sha256sums=('SKIP')
_tools="gendef genlib genidl genpeimg widl" # genstubdll

pkgver() {
  cd "${srcdir}/mingw-w64"
  local _major=$(head -n 16 mingw-w64-headers/crt/_mingw_mac.h | grep '__MINGW64_VERSION_MAJOR' | sed -e 's/.* //' | tr '\n' '.' | sed 's/.$/\n/')
  local _minor=$(head -n 16 mingw-w64-headers/crt/_mingw_mac.h | grep '__MINGW64_VERSION_MINOR' | sed -e 's/.* //' | tr '\n' '.' | sed 's/.$/\n/')
  local _rev=0
  printf "%s.%s.%s.%s.%s" ${_major} ${_minor} ${_rev} "$(git rev-list --count $_commit)" "$(git rev-parse --short $_commit)"
}

prepare() {
  cd "${srcdir}/mingw-w64"
  #git am "${srcdir}/0001-widl-Relocate-DEFAULT_INCLUDE_DIR.patch"
}

build() {
  local cur=
  for cur in ${_tools}; do
    plain "Building ${cur} ..."
    [[ -d ${srcdir}/${MINGW_CHOST}-${cur} ]] && rm -rf ${srcdir}/${MINGW_CHOST}-${cur}
    mkdir -p ${srcdir}/${MINGW_CHOST}-${cur}
    cd ${srcdir}/${MINGW_CHOST}-${cur}
    ${srcdir}/mingw-w64/mingw-w64-tools/${cur}/configure \
      --prefix=${MINGW_PREFIX} \
      --build=${MINGW_CHOST} \
      --host=${MINGW_CHOST} \
      --with-mangle=${MINGW_PREFIX}
    make
  done
}

package() {
  local cur=
  for cur in ${_tools}; do
    plain "Installing ${cur} ..."
    cd ${srcdir}/${MINGW_CHOST}-${cur}
    make DESTDIR=${pkgdir} install
    if [[ -f "${srcdir}/mingw-w64/mingw-w64-tools/${cur}"/COPYING ]]; then
      install -Dm644 ${srcdir}/mingw-w64/mingw-w64-tools/${cur}/COPYING ${pkgdir}${MINGW_PREFIX}/share/licenses/mingw-w64-tools/COPYING.${cur}
    fi
  done
}
